<?php

namespace App\Http\Controllers\Author;

use App\Http\Controllers\Controller;
use App\Models\Post;
use App\Models\Category;
use App\Models\Tag;
use App\Services\PostService;
use App\Services\UploadService;
use App\Http\Requests\StorePostRequest;
use App\Http\Requests\UpdatePostRequest;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Illuminate\Support\Facades\Auth;

/**
 * 作者文章控制器
 * 
 * 职责：
 * - 处理作者文章相关的HTTP请求
 * - 调用 PostService 和 UploadService 处理业务逻辑
 * - 返回视图和重定向
 */
class PostController extends Controller
{
    /**
     * 文章服务
     * 
     * @var PostService
     */
    protected PostService $postService;

    /**
     * 上传服务
     * 
     * @var UploadService
     */
    protected UploadService $uploadService;

    /**
     * 构造器
     */
    public function __construct(PostService $postService, UploadService $uploadService)
    {
        $this->middleware('auth');
        $this->postService = $postService;
        $this->uploadService = $uploadService;
    }

    /**
     * 显示文章列表
     * 
     * @param Request $request
     * @return \Inertia\Response
     */
    public function index(Request $request)
    {
        // 调用服务层获取作者文章列表
        $posts = $this->postService->getAuthorPosts(
            $request->only(['search', 'status', 'sort']),
            Auth::user(),
            10
        );

        // 获取作者统计信息
        $stats = $this->postService->getAuthorStats(Auth::user());

        return Inertia::render('Author/Posts/Index', [
            'posts' => $posts,
            'stats' => $stats,
            'filters' => $request->only(['search', 'status', 'sort'])
        ]);
    }

    /**
     * 显示编辑文章页面
     * 
     * @param Post $post
     * @return \Inertia\Response
     */
    public function edit(Post $post)
    {
        // 权限检查：只有作者本人或管理员可以编辑
        if (Auth::id() !== $post->author_id && !Auth::user()->can('manage posts')) {
            abort(403, '您没有编辑此文章的权限');
        }
        
        $post->load(['category', 'tags']);
        
        // 返回步骤式编辑器页面
        return Inertia::render('Author/Posts/Editor/ArticleEditor', [
            'post' => $post,
            'categories' => Category::select('id', 'name', 'slug')->get(),
            'tags' => Tag::select('id', 'name', 'slug')->get(),
            'user' => Auth::user()
        ]);
    }

    /**
     * 更新文章
     * 
     * @param UpdatePostRequest $request
     * @param Post $post
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update(UpdatePostRequest $request, Post $post)
    {
        // 权限检查
        $this->authorize('update', $post);

        // 处理图片上传（如果有文件上传）
        $data = $request->validated();
        if ($request->hasFile('featured_image')) {
            $uploadResult = $this->uploadService->uploadImage(
                $request->file('featured_image'),
                Auth::user()
            );
            $data['featured_image'] = $uploadResult['url'];
        } elseif ($request->input('featured_image_url')) {
            // 如果传的是 URL，直接使用
            $data['featured_image'] = $request->input('featured_image_url');
        }

        // 调用服务层更新文章
        $this->postService->update($post, $data, Auth::user());

        return redirect()->route('author.posts.index')
            ->with('success', '文章更新成功！');
    }

    /**
     * 删除文章
     * 
     * @param Post $post
     * @return \Illuminate\Http\RedirectResponse
     */
    public function destroy(Post $post)
    {
        // 权限检查在服务层中处理
        $this->postService->delete($post, Auth::user());

        return redirect()->route('author.posts.index')
            ->with('success', '文章删除成功！');
    }

    /**
     * 批量删除文章
     * 
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function batchDelete(Request $request)
    {
        $request->validate([
            'post_ids' => 'required|array',
            'post_ids.*' => 'exists:posts,id',
        ]);

        $count = $this->postService->batchDelete(
            $request->input('post_ids'),
            Auth::user()
        );

        return redirect()->route('author.posts.index')
            ->with('success', "成功删除 {$count} 篇文章");
    }

    /**
     * 批量更新文章状态
     * 
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function batchUpdateStatus(Request $request)
    {
        $request->validate([
            'post_ids' => 'required|array',
            'post_ids.*' => 'exists:posts,id',
            'status' => 'required|in:published,draft',
        ]);

        $count = $this->postService->batchUpdateStatus(
            $request->input('post_ids'),
            $request->input('status'),
            Auth::user()
        );

        $statusText = $request->input('status') === 'published' ? '发布' : '设为草稿';
        
        return redirect()->route('author.posts.index')
            ->with('success', "成功将 {$count} 篇文章{$statusText}");
    }

    /**
     * 显示创建文章页面
     * 
     * @return \Inertia\Response
     */
    public function create()
    {
        // 返回步骤式编辑器页面
        return Inertia::render('Author/Posts/Editor/ArticleEditor', [
            'categories' => Category::select('id', 'name', 'slug')->get(),
            'tags' => Tag::select('id', 'name', 'slug')->get(),
            'user' => Auth::user()
        ]);
    }

    /**
     * 保存新文章
     * 
     * @param StorePostRequest $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(StorePostRequest $request)
    {
        // 调试：输出接收到的原始数据
        \Log::info('=== 后端接收数据 ===', ['all' => $request->all()]);
        \Log::info('验证后数据', ['validated' => $request->validated()]);
        
        // 处理图片上传（如果有文件上传）
        $data = $request->validated();
        
        if ($request->hasFile('featured_image')) {
            $uploadResult = $this->uploadService->uploadImage(
                $request->file('featured_image'),
                Auth::user()
            );
            $data['featured_image'] = $uploadResult['url'];
        } elseif ($request->input('featured_image_url')) {
            // 如果传的是 URL，直接使用
            $data['featured_image'] = $request->input('featured_image_url');
            \Log::info('使用特色图片URL', ['url' => $data['featured_image']]);
        }

        \Log::info('处理后的数据', ['data' => $data]);

        // 调用服务层创建文章
        try {
            $post = $this->postService->create($data, Auth::user());
            \Log::info('文章创建成功', ['post_id' => $post->id]);
            
            return redirect()->route('author.posts.index')
                ->with('success', '文章创建成功！');
        } catch (\Exception $e) {
            \Log::error('文章创建失败', [
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            throw $e;
        }
    }

    /**
     * 从版本恢复文章
     * 
     * @param Post $post
     * @param \App\Models\PostRevision $revision
     * @return \Illuminate\Http\RedirectResponse
     */
    public function restore(Post $post, \App\Models\PostRevision $revision)
    {
        // 调用服务层恢复版本（权限检查在服务层中处理）
        $this->postService->restoreFromRevision($post, $revision, Auth::user());
        
        return redirect()->route('author.posts.edit', $post->slug)
            ->with('message', '文章已恢复到选定的版本');
    }
} 